#coding=utf-8
import time,datetime
import stutils

def get_price_from_soup(soup):

    def get_s(item):
        while True:
            r = item.string
            if r: return r.strip()
            item = item.contents[0]
            
    def get_data_from_row(row):

        r = []
        tds = row.findAll('td')

        for td in tds:
            r.append(get_s(td))

        if not r[0] :
            td0 = tds[0]
            rq = td0.contents[0].contents[1].string.strip()
            r[0] = rq

        return r

    r = []
    
    t = unicode('日期', 'u8')
    rq = soup.find(text = t)
    
    if not rq:return None
    
    table = rq.parent.parent.parent.parent.parent
    trs = table.findAll('tr')[2:]

    for tr in trs:
        d = get_data_from_row(tr)
        r.append(d)

    r.reverse()
    
    return r

def get_histprice_by_jd(code, year, jd):

    url = 'http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s.phtml?year=%s&jidu=%s'%(code, year, jd)
    s = stutils.get_soup(url)
    data = get_price_from_soup(s)
    
    return data
    
def get_yjs(sy, sjd, ey, ejd):
    #jd 代表季度
    #eg: get_yjs(2005,2) ==> [[]]
    #注意:all params are integer
    
    l = []
    if sy == ey:
        for jd in range(sjd, ejd+1):
            l.append([sy, jd])
        return l
        
    for jd in range(sjd, 5):
        l.append( [sy, jd] )
        
    years = range(sy+1, ey)    
    for y in years:
        for jd in range(1, 5):
            l.append( [y, jd] )
    
    for jd in range(1, ejd+1):
        l.append( [ey, jd] )
    
    l = [[str(i[0]), str(i[1])] for i in l]
    return l     
    
def get_jd(month):
    return (month-1)/3 + 1
            
def get_histprice(code, ipo, ey=2007 , ejd=4):
    sy = ipo.year
    sjd = get_jd( ipo.month)
    #print sy,sjd
    yjs = get_yjs(sy,sjd,ey,ejd)
    
    data = []
    for yj in yjs:
        d = get_histprice_by_jd(code, *yj)
        if not d:
            print "%s:not data in %s year,%s jidu"%(code, yj[0], yj[1])
            continue
        data.extend(d)
    return data

class NoPriceTodayError(Exception):
    def __str__(self):
        return "No Price Data today:%s"%datetime.date.today().isoformat()
    
def get_tdprice(code):
    '''获取当
天的price'''
    
    url = 'http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s.phtml'%code
    s = stutils.get_soup(url)
    data = get_price_from_soup(s) 
    if not data:
        #print "no data in this 季度"
        raise NoPriceTodayError()
            
    data = data[-1]
    
    td = datetime.date.today().isoformat()
    if data[0] != td:
        raise NoPriceTodayError()
    
    return data
